package com.lagou.work.task01.oom;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread extends Thread{

    private static Boolean flag = true;

    private Socket accept;

    public ServerThread(Socket accept){

        this.accept = accept;
    }
    @Override
    public void run() {

            BufferedReader bufferedReader = null;
            PrintStream printStream = null;
        try {
            InetAddress inetAddress = accept.getInetAddress();
            bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
            String line = null;
            ArrayList<char[]> myList = new ArrayList<char[]>();
            while (flag) {
                line = bufferedReader.readLine();
                char[] chars = line.toCharArray();
                try {
                    // 模拟内存溢出
                    myList.add(chars);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println("成功接收来自客户端 " + inetAddress + "共 "+(chars.length*2/(1024*1024))+"M 数据");
                printStream = new PrintStream(accept.getOutputStream());
                printStream.println("服务器接收客户端 " + inetAddress + "的消息成功!");
                if ("eixt".equals(line)){
                    System.out.println("客户端已下线！！！");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(accept, bufferedReader, printStream);
        }
    }
    /**
     * 关闭连接
     */
    private static void close( Socket socket, BufferedReader bufferedReader, PrintStream printStream){
        try {
            if(null != socket){
                socket.close();
            }
            if(null != printStream){
                printStream.close();
            }
            if(null != bufferedReader){
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
